<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Flickrwijit Hook - Load All Events
 *
 * PHP version 5
 * LICENSE: This source file is subject to LGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/copyleft/lesser.html
 * @author	   Ushahidi Team <team@ushahidi.com> 
 * @package	   Ushahidi - http://source.ushahididev.com
 * @copyright  Ushahidi - http://www.ushahidi.com
 * @license	   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License (LGPL) 
 */

class adminsection {

	/**
	 * Registers the main event add method
	 */
	public function __construct()
	{
		$this->db = Database::instance();
		$this->from_monitors = " ";
		// Hook into routing
		Event::add('system.pre_controller', array($this, 'add'));
	}

	/**
	 * Adds all the events to the main Ushahidi application
	 */
	public function add()
	{
		// Add a Sub-Nav Link
		Event::add('ushahidi_action.nav_admin_manage', array($this, 
			'_manage_link'));
		if (strripos(Router::$current_uri, "admin/reports/edit") !== false ) {
			
			Event::add('ushahidi_action.report_form_admin', array($this, 
				'_report_mode'));
			
			Event::add('ushahidi_action.report_form_admin', array($this, 
				'_update_report_mode'));
 			
			Event::add('ushahidi_action.report_edit', array($this, 
 				'_report_submit_admin'));
		
			Event::add('ushahidi_action.report_edit', array($this, 
 				'_delete_report_mode'));
			
			Event::add('ushahidi_action.report_delete',array($this,
				'_monitor_report_delete_admin'));
			Event::add('ushahidi_action.report_delete',array($this,
				'_crowd_report_delete_admin'));
			
			
		}elseif(strripos(Router::$current_uri, "admin/users") !== false) {
			// Hook into users report form
			Event::add('ushahidi_action.users_form_admin',array($this, 
				'_users_form'));
			
			//Hook into users submit form
			Event::add('ushahidi_action.users_add_admin', array($this,
				'_users_form_submit_admin'));
			
			//Hook into users edit action
			Event::add('ushahidi_action.users_edit_admin',array($this,
				'_update_users_admin_section'));
			
			//Hook into users view 
			Event::add('ushahidi_action.users_list_admin',array($this,
				'_users_display'));
			
			//Hook into users delete
			Event::add('ushahidi_action.users_delete_admin',array($this,
				'_users_delete_admin'));
			
			
		}else if( strripos(Router::$current_uri, "admin/reports") !== false ) {
			//Filter incident
			Event::add('ushahidi_filter.manipulate_incident', array($this,
				'_manipulate_incident'));
			
		}
		
		
	}
	
	public function _manage_link() 
	{
		$this_sub_page = Event::$data;
		
		echo ($this_sub_page == "adminsection") ? Kohana::lang('adminsection.adminsection_menu') : 
			"<a href=\"".url::site()."admin/manage/adminsection\">".Kohana::lang('adminsection.adminsection_menu')."</a>";	
	}
	
	public function _users_validate() {
		
	}
	
	public function _users_display() {
		
	}
	
	/**
	 * Detect reports from monitors
	 */
	public function _report_form_admin() {
		$auth = new Auth();	
		$admin_section = $this->_get_admin_section($_SESSION['auth_user']->id);
		
		//If user is a moderator, manipulate report query
		if ($auth->logged_in('login') ) {
			if( strcasecmp( $admin_section, "peacenet") == 0 ) {
				$this->from_monitors = "p";
			}
		}
		
		//Load the view
		$form = View::factory('admin/peacenet_form');
		$form->from_monitors = $this->from_monitors;
		$form->render(TRUE);
	}
	
	/**
	 * hook into users report form.
	 */
	public function _users_form() {
		// Load the View
	    $form = View::factory('admin/adminsection_users_form');
	        
	    $id = Event::$data;

	    // incase we are editing a user
	    if ($id)
	    {
	    	// Do We have an Existing Actionable Item for this Report?
	      	$adminsections = ORM::factory('adminsection')
	        	->where('user_id', $id)
	          	->select_list('id','adminsection_title');
	       	
	    } else {
	    	$adminsections = ORM::factory('adminsection')
	    		->where('adminsection_active', '1')
	    		->select_list('id','adminsection_title');
	    }   
	   	$form->adminsections = $adminsections;
	  	$form->render(TRUE);
		
	}
	
	/**
	 *  Add users to an admin section
	 */
	public function _users_form_submit_admin() {
		$post = Event::$data;
		
		$sql = "SELECT id FROM ".Kohana::config('database.default.table_prefix')."users WHERE username ='".$post->username."'";
		$user_id = $this->db->query($sql);
		if($post) {
			// pull user id from users table for insertion in adminsection.
			//Prevent dublicate entries.
			if($this->_get_user_id('adminsection_user',$user_id[0]->id) != $user_id[0]->id) {
				$adminsection = ORM::factory('adminsection_user');
				$adminsection->user_id = $user_id[0]->id;
				$adminsection->adminsection_id = $post->adminsection_title;
				$adminsection->save();
			}
		}
	}
	
	/**
	 * submt a report.
	 */
	public function _report_submit_admin() {
		
		$incident = Event::$data;
		
		if($_POST) {
			if(isset( $_POST['monitors'] ) && !empty($_POST['monitors']) && $_POST['monitors'] == "m" ) {
				if( $this->_get_incident_id('monitor_report',$incident->id) != $incident->id ) {
					$adminsection = ORM::factory('monitor_report');
					$adminsection->incident_id = $incident->id;
					$adminsection->save();
				}
				
			}else if( !empty($_POST['monitors']) && $_POST['monitors'] == "p") {  
				if($this->_get_incident_id('peacenet_report',$incident->id) != $incident->id){
					$adminsection = ORM::factory('peacenet_report');
					$adminsection->incident_id = $incident->id;
					$adminsection->save();
				}
			}else {
				if($this->_get_incident_id('crowd_report',$incident->id) != $incident->id){
					$adminsection = ORM::factory('crowd_report');
					$adminsection->incident_id = $incident->id;
					$adminsection->save();
				}
			}
		}
	}
	
	/**
	 * Get message coming from monitors
	 */
	public function _from_monitors() {
		$_SESSION['from_location'] = Event::$data;
	}
	
	public function _report_mode() {
		$incident_id = Event::$data;
		// get user login section
		
		$auth = new Auth();
		
		$existing_id = $this->_get_incident_id('report_mode', $incident_id );
		
		$user_id = $this->_get_user_id('report_mode',$_SESSION['auth_user']->id);
		
		if( ( $existing_id == $incident_id ) && 
			!empty($incident_id) && 
			$user_id != $_SESSION['auth_user']->id && 
			( !$auth->logged_in('superadmin') || !$auth->logged_in('admin') )) {
				url::redirect('admin/reports/');
		}
	}
	
	/**
	 * Manipulate view 
	 */
	public function _manipulate_incident() {
		$filter = Event::$data;
	
		$auth = new Auth();
			
		$admin_section = $this->_get_admin_section($_SESSION['auth_user']->id);
		
		//If user is a moderator, manipulate report query
		if ($auth->logged_in('login') ) {
				
			if( strcasecmp( $admin_section, "creco") == 0 ) {
				
				$incident_id = $this->_get_report('monitor_report');
				
				if( strcasecmp( $filter, "1=1" ) == 0 ) {
					$filter = "incident.id = $incident_id ";
				} else {
					$filter .= " AND ( ".Kohana::config('database.default.table_prefix')."incident.id = $incident_id )";
				}
				
				Event::$data = $filter;
				
			}else if(strcasecmp( $admin_section, "uraia") == 0 ){
				
				$incident_id = $this->_get_report('crowd_report');
				
				if( strcasecmp( $filter, "1=1" ) == 0 ) {
					$filter = "incident.id = $incident_id ";
				} else {
					$filter .= " AND ( ".Kohana::config('database.default.table_prefix')."incident.id = $incident_id )";
				}
				
				Event::$data = $filter;	
			}else if(strcasecmp( $admin_section, "peacenet") == 0 ){
				
				$incident_id = $this->_get_report('peacenet_report');
				
				if( strcasecmp( $filter, "1=1" ) == 0 ) {
					$filter = "incident.id = $incident_id ";
				} else {
					$filter .= " AND ( ".Kohana::config('database.default.table_prefix')."incident.id = $incident_id )";
				}
				
				Event::$data = $filter;	
			} 
			
		} else {
			Event::$data = $filter;
			
		}
		
	}
	
	/**
	 * Get admin section title.
	 */
	public function _get_admin_section($user_id){
		
		$admin_section = ORM::factory('adminsection_user')
		->where('user_id',$user_id)->orderby('adminsection_id')
		->join('adminsection','adminsection_users.adminsection_id','adminsection.id','INNER')
		->find();
		
		return $admin_section->adminsection->adminsection_title;
	}
	
	/**
	 * Delete from adminsection table
	 */
	public function _users_delete_admin() {
		$users = Event::$data;
		
		$this->db->delete('adminsection_users', array('user_id' => $users->id));
		
	}
	
	/**
	 * Delete report id from monitor_report
	 */
	public function _monitor_report_delete_admin() {
		$incident = Event::$data;
		
		$this->db->delete('monitor_report', array('incident_id' => $incident));
		
	}
	
    /**
	 * Delete report id from crowd_report
	 */
	public function _crowd_report_delete_admin() {
		$incident = Event::$data;
		
		$this->db->delete('crowd_report', array('incident_id' => $incident));
		
	}
	
	/**
	 * Delete report id from crowd_report
	 */
	public function _peacenet_report_delete_admin() {
		$incident = Event::$data;
		$this->db->delete('peacenet_report', array('incident_id' => $incident));
		
	}
	
	
	/**
	 * Update an admin section
	 */
	public function _update_users_admin_section() {
		$post = Event::$data;
		
		if($post) {
			$status = $this->db->update('adminsection_users',
				array('adminsection_id' => $post->adminsection_title),
				array('user_id' => $post->user_id));

			if( count($status) == 0 ){
				$adminsection = ORM::factory('adminsection_user');
				$adminsection->user_id = $post->user_id;
				$adminsection->adminsection_id = $post->adminsection_title;
				$adminsection->save();				
			}
		}
	}
	
	/**
	 * Update the mode of a report
	 * @param unknown_type $report_id
	 */
	public function _delete_report_mode() {
		$incident = Event::$data;
		$this->db->delete('report_mode', array('incident_id' => $incident));
	}
	
	/**
	 * insert the mode of a report
	 */
	public function _update_report_mode() {
		
		$incident_id = Event::$data;
		
		if( $this->_get_incident_id('report_mode', $incident_id ) != $incident_id ) {
			$report_mode = ORM::factory('report_mode');
			$report_mode->incident_id = $incident_id;
			$report_mode->user_id = $_SESSION['auth_user']->id;		
			$report_mode->save();
		}
		
	}
	
	/**
	 * Check if a report ID already exist in the db.
	 * @param report id
	 * @param table name
	 */
	public function _get_incident_id($table_name, $report_id) {
		$incident_id = ORM::factory($table_name)->where('incident_id',$report_id)->find();
		return $incident_id->incident_id;
	}
	
	/**
	 * Get reports
	 */
	public function _get_report($table_name) {
		$incident_id = ORM::factory($table_name)->find();
		return $incident_id->incident_id;
	}
	
	/**
	 * Get user id
	 */
	public function _get_user_id($table_name, $user_id ) {
		$user_id = ORM::factory($table_name)->where('user_id',$user_id)->find();
		return $user_id->user_id;
	}

}

new adminsection;

